class TerminalKeynote::Renderer
  TRANSITIONS_TIME = 0.3
  MAX_CHAR_DELAY   = 0.002

  def render_slide(slide)
    return unless slide

    @row = slide.top_margin
    @result = ''

    slide.blocks.each do |block|
      render_block(block)
    end

    transition
  end

  def clear
    print "\e[2J\e[H"
  end

private

  def transition
    pause  = [TRANSITIONS_TIME / @result.length, MAX_CHAR_DELAY].min

    @result.each_char do |c|
      print c
      sleep pause # old-school touch: running cursor
    end
  end

  def render_block(block)
    block.lines.each do |line|
      render_line(line)
    end
  end

  def render_line(line)
    @result << "\e[#{@row};#{line.left_margin}H#{line}"
    @row += 1
  end
end
